package leetcode.d_1_99;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

// https://leetcode.cn/problems/combination-sum/description/
// 组合总和
public class P39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new LinkedList<>();
        trackback(candidates, target, res, new LinkedList<>(), 0, target);
        return res;
    }

    public void trackback(int[] candidates, int target, List<List<Integer>> res, LinkedList<Integer> curRes, int idx, int sum) {
        if (sum == 0) {
            res.add(new ArrayList<>(curRes));
            return;
        }

        if (idx >= candidates.length) {
            return;
        }

        // 不取当前元素
        trackback(candidates, target, res, curRes, idx+1, sum);
        // 取当前元素
        if (candidates[idx] <= sum) {
            curRes.add(candidates[idx]);
            trackback(candidates, target, res, curRes, idx, sum-candidates[idx]);
            curRes.removeLast();
        }
    }

    public static void main(String[] args) {
        P39 test = new P39();
        System.out.println(test.combinationSum(new int[]{2,3,6,7}, 7) );
    }
}
